package jee.boot.oauth.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jee.boot.common.basic.result.MessageCodeHelper;
import jee.boot.common.basic.result.ResponseMessage;
import jee.boot.common.basic.result.Result;
import jee.boot.common.utils.SpringContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证信息重写
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Throwable cause = authException.getCause();
        String msg = authException.getMessage();
        if (cause instanceof InvalidTokenException) {
            msg = getMessageCodeHelper().getMessage(1115);
        }
        ResponseMessage<Object> message = Result.unAuthorized(msg);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(message));
        response.getWriter().flush();
        response.getWriter().close();
    }
   private  MessageCodeHelper getMessageCodeHelper(){
        MessageCodeHelper bean = SpringContextHolder.getApplicationContext().getBean(MessageCodeHelper.class);
        return bean;
    }
}